package example.interceptor;

import example.model.AdminUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by zhouzixiong1 on 2017/9/1.
 */
public class LoginInterceptor implements HandlerInterceptor{

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session =request.getSession();
        String[] allowUrls =new String[]{"/AMenu/alogin","/AMenu/nlogin","/AMenu/aSignInAdminUser","/AdminUser/adminUserLogin","NormalUser/normalUserLogin","/AdminUser/adminUserSignIn"};
        String url =request.getRequestURL().toString();
        AdminUser adminUser = (AdminUser) session.getAttribute("currentUser");
        for (String strUrl : allowUrls) {
            if(url.contains(strUrl))
            {
                return true;
            }
        }
        if(adminUser==null){
            String[] homeUrls = url.split("8080");
            response.sendRedirect(homeUrls[0]+ "8080" +"/AMenu/alogin");
            return false;
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
